<?php
class Exts_Controller_Cron extends Exts_Controller_Action
{

	/**
	 * A partir de la configuracion definidad en el config default.ini
	 *
	 * Genera los archivos de sitemaps.
	 *
	 *
	 * [sitemap]
	 *	itemCountPerPage = 1000
	 *	destination = APPLICATION_PATH "/../public/sitemaps/"
	 *
	 *	models.tag.model = Exts_Models_Tags
	 *	models.tag.url = "/tags/[1]"
	 *	models.tag.params[1] = name
     *	models.tag.priority = "0.5"
	 *
	 *
	 *
	 */
    public function sitemapGeneratorAction()
	{
		$sitemapHeader = '<?xml version="1.0" encoding="UTF-8"?>'
			. '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
		$sitemapFooter = '</urlset>';

		$sitemapUrl = '<url><loc>URL</loc><priority>PRIORITY</priority></url>';

		$mapsHeader = '<?xml version="1.0" encoding="UTF-8"?>'
			.'<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

		$mapsFooter = '</sitemapindex>';

		$sitemapConfig = $this->_config->sitemap;

		/**
		 * Consigo todos los modelos de la config que necesitan tener un sitemap.
		 * Estos se configuran el archivo config.default.ini de cada ambiente.
		 * [sitemap]
		 * tag.url = "/url/$1"
		 *
		 */
		foreach( $sitemapConfig->models as $name => $prop ) {
			$model = new $prop->model();
			$fields = $model->getAllToSitemap();

			/**
			 * El paginador nos da una mano, para separar los sitemaps en x
			 * cantidad de links por sitemap.
			 */
			$paginator = Zend_Paginator::factory( $fields );
			$paginator->setItemCountPerPage(
				$sitemapConfig->itemCountPerPage
			);
			for( $i=1; $i<= count($paginator); $i++ ) {
				$mapsUrl = "/sitemaps/" . $fields[$i];
				$paginator->setCurrentPageNumber($i);
				$urls = '';
				foreach( $paginator as $item ) {
					$url = $prop->url;
					for( $j=1; $j<=count( $prop->params ); $j++ ) {
						$url = ereg_replace(
							"\[$j\]" ,
							$this->view->seoUrl( $item[$prop->params->{$j}] ),
							$url
						);
					}
					$url = $sitemapConfig->baseUrl . $url;
					$url = ereg_replace( "URL", $url, $sitemapUrl );
					$url = ereg_replace(
						"PRIORITY",
						$prop->priority,
						$url
					);
					$urls .= $url;

				}
				$content = $sitemapHeader. $urls.$sitemapFooter;

				$fileName = $sitemapConfig->destination . $name . '-' .$i .'.xml';
				file_put_contents($fileName, $content );
				$maps[] = $name . '-' .$i .'.xml';
			}

		}

		print_r($maps);exit;

		$maps = '<sitemap>
			<loc>http://www.buscouniversidad.com.ar/sitemaps/search_1.xml</loc>
		</sitemap>';



	}
    
}